import React from 'react';
import { connect } from 'dva';
import queryString from 'query-string';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BatchUpload from '../../components/BatchUpload/Index';
import FileUpload from '../../components/BatchUpload/Upload';
import Finish from '../../components/BatchUpload/Finish';

@connect(({ batchcontact, loading }) => ({
  uploading: loading.effects['batchcontact/uploadFileWithProgress'],
  currentStep: batchcontact.currentStep,
  progressPercent: batchcontact.progressPercent,
  resultInfo: batchcontact.resultInfo,
  showProgress: batchcontact.showProgress,
}))
class Batch extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: null,
    };
  }

  componentDidMount() {
    const { location } = this.props;
    const { activeKey } = queryString.parse(location.search);
    this.setState({ activeKey });
  }

  componentWillUnmount() {
    this.clearModel();
  }

  // 重置model
  clearModel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'batchcontact/updateModelData',
      payload: {
        currentStep: 0,
        progressPercent: 0,
        showProgress: false,
      },
    });
  };

  // 设置当前位置
  setCurrentstep = currentStep => {
    const { dispatch } = this.props;
    dispatch({
      type: 'batchcontact/updateModelData',
      payload: { currentStep },
    });
    if (!currentStep) {
      this.clearModel();
    }
  };

  // 上传文件：需要携带参数即传：batchQuery
  uploadFile = formData => {
    const { dispatch } = this.props;
    dispatch({
      type: 'batchcontact/uploadFileWithProgress',
      payload: {
        params: formData,
      },
    });
  };

  render() {
    const { uploading, currentStep, showProgress, progressPercent, resultInfo } = this.props;
    const { activeKey } = this.state;
    return (
      <PageHeaderWrapper>
        <BatchUpload currentStep={currentStep}>
          <FileUpload
            title="上传文件"
            currentStep={currentStep}
            setCurrentstep={this.setCurrentstep}
            downloadTempInfo={{
              // 下载模板信息
              params: {
                curStep: activeKey,
              },
              url: '/esApi/entry/expEntryContactTemp',
              type: 'POST',
            }}
            uploadFile={this.uploadFile}
            uploading={uploading}
            // 展示进度条需要的数据
            progressPercent={progressPercent || 0}
            progressVisible={showProgress}
            progressTitle="批量联系"
          />
          <Finish title="完成" resultInfo={resultInfo} setCurrentstep={this.setCurrentstep} />
        </BatchUpload>
      </PageHeaderWrapper>
    );
  }
}

export default Batch;
